package com.heima.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.dtos.UserSearchDto;
import com.heima.search.service.ApUserSearchService;
import com.heima.search.service.ArticleSearchService;
import com.heima.utils.common.ThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.Operator;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class ArticleSearchServiceImpl implements ArticleSearchService {

    @Autowired
    private RestHighLevelClient client;

    @Autowired
    private ApUserSearchService apUserSearchService;

    @Override
    public ResponseResult search(UserSearchDto dto) throws IOException {
        //1.判断搜索关键词是否为空
        if(StringUtils.isBlank(dto.getSearchWords())){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }


        //2.异步保存搜索记录
        Integer userId = ThreadLocalUtil.getUserId();
        if(userId>0 && dto.getFromIndex()==0){
            apUserSearchService.insert(dto.getSearchWords(),userId);
        }

        SearchRequest searchRequest = new SearchRequest("app_info_article");
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();

        //3.构建搜索条件：组合搜索（多字段搜索和范围搜索）
        //3.1 创建组合搜索条件构建器
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();

        //3.2 设置搜索条件1：根据title和content进行关键词的多字段搜索，结果集要求并集
        boolQueryBuilder.must(QueryBuilders.queryStringQuery(dto.getSearchWords()).field("title").field("content").defaultOperator(Operator.OR));

        //3.3 设置搜索条件2：根据publishTime小于最小时间搜索
        boolQueryBuilder.filter(QueryBuilders.rangeQuery("publishTime").lt(dto.getMinBehotTime().getTime()));

        searchSourceBuilder.query(boolQueryBuilder);

        //4.设置结果要求：排序、限制条数、title高亮
        //34.1 设置结果要求1：根据publishTime倒排序
        searchSourceBuilder.sort("publishTime", SortOrder.DESC);

        //4.2 设置结果要求2：根据请求参数限制查询条数
        if(dto.getPageSize()<=0){
            dto.setPageSize(10);
        }
        searchSourceBuilder.size(dto.getPageSize());

        //4.3 设置结果要求3：需要在title结果中出现的词条前后加上高亮标签
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.field("title");//高亮字段
        highlightBuilder.preTags("<font style='color:red;font-size:inherit;' >");//前置HTML标签
        highlightBuilder.postTags("</font>");//后置HTML标签

        searchSourceBuilder.highlighter(highlightBuilder);

        searchRequest.source(searchSourceBuilder);

        //5.调用client的search方法执行搜索
        SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);

        //6.解析搜索结果数据，封装文章列表

        //6.1 获取二级SearchHits的数组
        SearchHit[] searchHits = searchResponse.getHits().getHits();

        //6.2 遍历命中的SearchHits数组得到每个文档对象
        List<Map> searchArticleList =new ArrayList<>();
        if(searchHits!=null && searchHits.length>0){
            for (SearchHit hit : searchHits) {
                //从每个文档对象中获取JSON原始数据
                String articleJSON = hit.getSourceAsString();

                Map articleMap = JSON.parseObject(articleJSON, Map.class);

                //从每个文档对象中获取高亮的title中数据
                Map<String, HighlightField> highlightFields = hit.getHighlightFields();
                if(highlightFields!=null && highlightFields.size()>0){
                    HighlightField highlightField = highlightFields.get("title");
                    Text[] fragments = highlightField.getFragments();
                    if(fragments!=null && fragments.length>0){
                        String highlightTitle = fragments[0].toString();//带高亮标签的title的值
                        articleMap.put("h_title",highlightTitle);
                    } else {
                        articleMap.put("h_title",articleMap.get("title"));
                    }
                } else {
                    articleMap.put("h_title",articleMap.get("title"));
                }

                searchArticleList.add(articleMap);
            }
        }

        return ResponseResult.okResult(searchArticleList);
    }
}
